package com.hjimi.ski.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;


import com.hjimi.ski.app.MyApplication;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import static android.content.Context.INPUT_METHOD_SERVICE;


/**
 * 作者 杨晓楠
 * 时间 2018/11/5 9:57
 * 文件 as_fth_business
 * 描述
 */

public class Mutils {
    public static Context getContext() {
        return MyApplication.getInstance();
    }

    public static Resources getResources() {
        return getContext().getResources();
    }

    public static void setFullscreen(Activity activity, boolean isShowStatusBar, boolean isShowNavigationBar) {
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

        if (!isShowStatusBar) {
            uiOptions |= View.SYSTEM_UI_FLAG_FULLSCREEN;
        }
        if (!isShowNavigationBar) {
            uiOptions |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        }
        activity.getWindow().getDecorView().setSystemUiVisibility(uiOptions);

        //隐藏标题栏
        // getSupportActionBar().hide();
        setNavigationStatusColor(activity, Color.TRANSPARENT);
    }

    /**
     * 返回当前屏幕是否为竖屏。
     * @param context
     * @return 当且仅当当前屏幕为竖屏时返回true,否则返回false。
     */
    public static boolean isScreenOriatationPortrait(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    public static final int TYPE_ROTATE_0 = 0;
    public static final int TYPE_ROTATE_90 = 1;
    public static final int TYPE_ROTATE_180 = 2;
    public static byte[] rgbBytesRotateClockwise(byte[] rgbBytes, int width, int height, int rotateType) {
        byte[] _newRgbBytes = rgbBytes.clone();
        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {

//                if (rotateType == TYPE_ROTATE_90) {
//                    _newRgbBytes[(i * height + (height - 1 - j)) * 3] = rgbBytes[(j * width + i) * 3];
//                    _newRgbBytes[(i * height + (height - 1 - j)) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
//                    _newRgbBytes[(i * height + (height - 1 - j)) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
//                } else if (rotateType == TYPE_ROTATE_180) {
//                    _newRgbBytes[((height - 1 - j) * width + (width - 1 - i)) * 3] = rgbBytes[(j * width + i) * 3];
//                    _newRgbBytes[((height - 1 - j) * width + (width - 1 - i)) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
//                    _newRgbBytes[((height - 1 - j) * width + (width - 1 - i)) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
//                } else {
//                    _newRgbBytes[((width - 1 - i) * height + j) * 3] = rgbBytes[(j * width + i) * 3];
//                    _newRgbBytes[((width - 1 - i) * height + j) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
//                    _newRgbBytes[((width - 1 - i) * height + j) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
//                }

                if (rotateType == TYPE_ROTATE_90) {
                    _newRgbBytes[(i * height + (height - 1 - j)) * 3] = rgbBytes[(j * width + i) * 3];
                    _newRgbBytes[(i * height + (height - 1 - j)) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
                    _newRgbBytes[(i * height + (height - 1 - j)) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
                } else if (rotateType == TYPE_ROTATE_180) {
                    _newRgbBytes[((height - 1 - j) * width + (width - 1 - i)) * 3] = rgbBytes[(j * width + i) * 3];
                    _newRgbBytes[((height - 1 - j) * width + (width - 1 - i)) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
                    _newRgbBytes[((height - 1 - j) * width + (width - 1 - i)) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
                } else if (rotateType == TYPE_ROTATE_0) {
                    _newRgbBytes[(j * width + i) * 3] = rgbBytes[(j * width + i) * 3];
                    _newRgbBytes[(j * width + i) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
                    _newRgbBytes[(j * width + i) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
                } else {
                    _newRgbBytes[((width - 1 - i) * height + j) * 3] = rgbBytes[(j * width + i) * 3];
                    _newRgbBytes[((width - 1 - i) * height + j) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
                    _newRgbBytes[((width - 1 - i) * height + j) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
                }
            }
        }

        return _newRgbBytes;
    }

    public static void setNavigationStatusColor(Activity activity, int color) {
        //VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
        if (Build.VERSION.SDK_INT >= 21) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            activity.getWindow().setNavigationBarColor(color);
            activity.getWindow().setStatusBarColor(color);
        }
    }

    public static  double getDuration(String filePath){
        MediaPlayer player = new MediaPlayer();
        try {
            player.setDataSource(filePath);  //filePath为文件的路径
            player.prepare();
        } catch (Exception e) {
            Log.d("sunyan", "getDuration: "+e.toString());
        }
        double duration= player.getDuration();//获取媒体文件时长
        Log.d("sunyan", "getDuration: " + duration);
        player.release();//记得释放资源
        return duration;
    }


    public static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    public static Bitmap getViewBitmap(View view) {
        view.setDrawingCacheEnabled(true);
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0,0,view.getMeasuredWidth(),view.getMeasuredHeight());
        view.buildDrawingCache();
        return Bitmap.createBitmap(view.getDrawingCache());
    }


    public static String formatBigNum(String num) {
//        if (StringUtils.isEmpty(num)) {
//            // 数据为空直接返回0
//            return "0";
//        }
        try {
            StringBuffer sb = new StringBuffer();


//            BigDecimal b0 = new BigDecimal("1000");
            BigDecimal b1 = new BigDecimal("10000");
            BigDecimal b2 = new BigDecimal("100000000");
            BigDecimal b3 = new BigDecimal(num);

            String formatedNum = "";//输出结果
            String unit = "";//单位

            if (b3.compareTo(b1) == -1) {
                sb.append(b3.toString());
            }  else if ((b3.compareTo(b1) == 0 && b3.compareTo(b1) == 1)
                    || b3.compareTo(b2) == -1) {
                formatedNum = b3.divide(b1).toString();
                unit = "万";
            } else if (b3.compareTo(b2) == 0 || b3.compareTo(b2) == 1) {
                formatedNum = b3.divide(b2).toString();
                unit = "亿";
            }
            if (!"".equals(formatedNum)) {
                int i = formatedNum.indexOf(".");
                if (i == -1) {
                    sb.append(formatedNum).append(unit);
                } else {
                    i = i + 1;
                    String v = formatedNum.substring(i, i + 1);
                    if (!v.equals("0")) {
                        sb.append(formatedNum.substring(0, i + 1)).append(unit);
                    } else {
                        sb.append(formatedNum.substring(0, i - 1)).append(unit);
                    }
                }
            }
            if (sb.length() == 0)
                return "0";
            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return num;
        }
    }


    //逗号分隔的字符串转list
    public static List<String> getListStr(String str) {
        String[] strs = str.split(",");
        List<String> strList= Arrays.asList(strs);
        ArrayList<String> arrayList= new ArrayList<>(strList);
        return arrayList;
    }

    //hashset转字符串
    public static String getString(HashSet<String> hashSet){
        List<String> list = new ArrayList<>();
        Iterator<String> iterator = hashSet.iterator();

        while (iterator.hasNext()){
            list.add(iterator.next());
        }
        String str = "";
        for(int i=0;i<list.size();i++){
            if(i==list.size()-1){
                str+=list.get(i);
            }else {
                str = list.get(i)+",";
            }
        }
        if(str.startsWith(",")){
            str = str.substring(1);
        }
        return str;
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(long s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(s);
        res = simpleDateFormat.format(date);
        return res;
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate11(long s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        Date date = new Date(s);
        res = simpleDateFormat.format(date);
        return res;
    }

    public static String strToStr2(String str) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d = sf.parse(str);
        return sf.format(d);
    }

    public static String strToStr(String str) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sf.parse(str);
        return sf.format(d);
    }

    public static String strToStr1(String str) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sf.parse(str);
        return sf.format(d);
    }

    public static String strToStr3(String str) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sf.parse(str);
        String a = sf.format(d).substring(5);
        return a;
    }

    public static String dealDateFormat(String oldDate) {
        Date date1 = null;
        DateFormat df2 = null;
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            Date date = df.parse(oldDate);
            SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            date1 = df1.parse(date.toString());
            df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return df2.format(date1);
    }

    public static long getSystemTime() {
        return System.currentTimeMillis();
    }

    /**
     * 判断是否为奇数
     * @param a
     * @return
     */
    public static boolean isOdd(int a) {
        if ((a & 1) != 0) { //奇数
            return true;
        }
        return false;
    }

    /**
     * 复制内容到剪贴板
     *
     * @param content
     * @param context
     */
    public static  void copyContentToClipboard(String content, Context context) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", content);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        ToastUtils.show("已复制");
    }

//    /**
//     * base64解密
//     * @param str 加密后的字符串
//     * @return
//     */
//    public static String base64Decoder(String str){
//        String str2 = new String(Base64.decode(str.getBytes()));
//        return str2;
//
//    }
//
//    /**
//     * 加密
//     * @param str
//     * @return
//     */
//    public static String base64Encoder( String str) {
//        String str1 = new String(Base64.encode(str.getBytes()));
//        return str1;
//    }

//    public static Bitmap getNetVideoBitmap(String videoUrl) {
//        Bitmap bitmap = null;
//
//        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
//        try {
//            //根据url获取缩略图
//            retriever.setDataSource(videoUrl, new HashMap());
//            //获得第一帧图片
//            bitmap = retriever.getFrameAtTime();
//        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
//        } finally {
//            retriever.release();
//        }
//        return bitmap;
//    }

    /**
     * dip转换px
     */
    public static int dip2px(int dip) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    /**
     * pxz转换dip
     */
    public static int px2dip(int px) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     */
    public static int px2sp(float pxValue) {
        final float fontScale = getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     */
    public static int sp2px(float spValue) {
        final float fontScale = getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 网络是否可用
     * 检测当的网络（WLAN、3G/2G）状态
     *
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable() {
        ConnectivityManager connectivity = (ConnectivityManager) getContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

    //............................

    /**
     * 创建带随机颜色选择器TextView
     */
    public static TextView createRandomColorSelectorTextView() {
        final TextView textView = new TextView(Mutils.getContext());
        textView.setTextColor(Color.parseColor("#de6838"));
        textView.setPadding(dip2px(10), dip2px(4), dip2px(10), dip2px(4));
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(dip2px(45));


        textView.setBackgroundDrawable(createRandomColorSelector());
//
        return textView;
    }

    /**
     * 创建随机颜色选择器
     */
    private static Drawable createRandomColorSelector() {
        StateListDrawable stateListDrawable = new StateListDrawable();  // 创建选择器类型的Drawable
        int[] pressState = {android.R.attr.state_pressed, android.R.attr.state_enabled};
        Drawable pressedDrawable = createRandomColorShape();
        stateListDrawable.addState(pressState, pressedDrawable);    // 设置按下状态和对应显示的Drawable

        int[] normalState = {};
        Drawable normalDrawable = createRandomColorShape();
        stateListDrawable.addState(normalState, normalDrawable);    // 设置正常状态和对应显示的Drawable
        return stateListDrawable;
    }

    /**
     * 获取本地软件版本号
     */
    public static int getLocalVersion(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }


    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    private static Drawable createRandomColorShape() {
        GradientDrawable gradientDrawable = new GradientDrawable(); // 创建图形Drawable
        gradientDrawable.setShape(GradientDrawable.RECTANGLE);      // 设置形状为矩形
        gradientDrawable.setCornerRadius(dip2px(0));                 // 设置图形圆角
        gradientDrawable.setColor(Color.WHITE);             // 设置图形颜色
        return gradientDrawable;
    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 获取当前系统时间
    public static String getNowSystemTime() {
        Calendar calendar = Calendar.getInstance();
        int mYear = calendar.get(Calendar.YEAR); // 获取当前年份
        int mMonth = calendar.get(Calendar.MONTH) + 1;// 获取当前月份
        int mDay = calendar.get(Calendar.DAY_OF_MONTH);// 获取当日期
        int mHour = calendar.get(Calendar.HOUR_OF_DAY);//时
        int mMinute = calendar.get(Calendar.MINUTE);//分
        int mSecond = calendar.get(Calendar.SECOND);//秒
        String nowTime = "" + mYear + "" + mMonth + "" + mDay + "" + mHour + "" + mMinute + "" + mSecond + "" + ((Math.random() * 9 + 1) * 10000);
        return nowTime;
    }

    public static String a(long b) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd HH:mm:ss");//初始化Formatter的转换格式。
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        String hms = formatter.format(b);
        return hms;
    }

    public static String getGapTime(long time){
        long hours = time / (1000 * 60 * 60);
        long minutes = (time-hours*(1000 * 60 * 60 ))/(1000* 60);
        long second = (time-hours*(1000 * 60 * 60 )-minutes*(1000 * 60 ))/1000;
        String diffTime="";
        if(minutes<10){
            diffTime=hours+":0"+minutes;
        }else{
            diffTime=hours+":"+minutes;
        }
        if(second<10){
            diffTime=diffTime+":0"+second;
        }else{
            diffTime=diffTime+":"+second;
        }
        return diffTime;
    }


    //获取当前时间的时间戳
    public static long getNowTime(String str) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(str);
        long ts = date.getTime();
        return ts;
    }

    //返回格式化后的银行卡号
    public static String getBankCardNo(String number) {
        StringBuffer stringBuffer = new StringBuffer(number);
        int length = stringBuffer.length();
        if (length == 16) {
            stringBuffer.replace(0, 12, "**** **** **** ");
        } else if (length == 18) {
            stringBuffer.replace(0, 14, "**** **** **** ");
        } else if (length == 19) {
            stringBuffer.replace(0, 15, "**** **** **** ");
        }
        return stringBuffer.toString();
    }

    //返回银行卡号后四位
    public static String getCardLastFour(String number) {
        int length = number.length();
        String str = "";
        if (length == 16) {
            str = number.substring(12, 16);
        } else if (length == 18) {
            str = number.substring(14, 18);
        } else if (length == 19) {
            str = number.substring(15, 19);
        }
        return str;
    }

    //限制输入框小数点后只能输入两位
    public static void setPricePoint(final EditText editText, final String money) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }

                if (s.length() > 6 && s.charAt(6) == '.') {
                    editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(9)});
                } else if (s.length() == 7 && s.charAt(5) == '.') {
                    editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(8)});
                } else {
                    editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(7)});
                }

                String editable = editText.getText().toString();
                String str = stringFilter(editable.toString());
                if (!editable.equals(str)) {
                    editText.setText(str);
                    //设置新的光标所在位置
                    editText.setSelection(str.length());
                }

                //将输入的金额与余额进行比对
                if (!TextUtils.isEmpty(str)) {
                    double dStr = new Double(str);
                    double dMoney = new Double(money);
                    if (dStr > dMoney) {
                        editText.setText(money);
                        //设置新的光标所在位置
                        editText.setSelection(money.length());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
        });
    }

    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只能输入一次小数点
        int times = 0;
        int pointIndex = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '.') {
                times++;
                pointIndex = i;
            }
        }
        StringBuilder stringBuilder = new StringBuilder(str);
        if (times > 1) {
            stringBuilder.replace(pointIndex, pointIndex + 1, "");
            return stringBuilder.toString();
        } else {
            return str;
        }
    }

    /**
     * 关闭软键盘
     *
     * @param mEditText //输入框
     * @param mContext  //上下文
     */
    public static void closeKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }


    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void showInput(Context context, final EditText et) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }


    /**
     * 判断当前软键盘是否打开
     *
     * @param activity
     * @return
     */
    public static boolean isSoftInputShow(Activity activity) {
        // 虚拟键盘隐藏 判断view是否为空
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            // 隐藏虚拟键盘
            InputMethodManager inputmanger = (InputMethodManager) activity
                    .getSystemService(INPUT_METHOD_SERVICE);
//       inputmanger.hideSoftInputFromWindow(view.getWindowToken(),0);

            return inputmanger.isActive() && activity.getWindow().getCurrentFocus() != null;
        }
        return false;
    }

    /**
     * 利用MD5进行加密
     *
     * @param string 待加密的字符串
     * @return 加密后的字符串
     */
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    //获取系统的日期
    public static int getDate(String date) {
        Calendar calendar = Calendar.getInstance();
        switch (date) {
            case "year":
                return calendar.get(Calendar.YEAR);
            case "month":
                return calendar.get(Calendar.MONTH) + 1;
            case "day":
                return calendar.get(Calendar.DAY_OF_MONTH);
            case "hour":
                return calendar.get(Calendar.HOUR_OF_DAY);
            case "minute":
                return calendar.get(Calendar.MINUTE);
            default:
                return calendar.get(Calendar.SECOND);
        }
    }

    //状态栏颜色
    public static void changeTitleColor(Window window) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.setStatusBarColor(Color.parseColor("#ffffff"));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else if (Build.VERSION.SDK_INT >= 21) {
            window.setStatusBarColor(Color.parseColor("#9e9e9e"));
        }
    }

    //设置Toast时间
    public static void showMyToast(final Toast toast, final int cnt) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        }, 0, 3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt);
    }


//    public static void yuyin(Context context, String text) {
//        //1.创建 SpeechSynthesizer 对象, 第二个参数：本地合成时传 InitListener
//        SpeechSynthesizer mTts = SpeechSynthesizer.createSynthesizer(context, null);
//        //2.合成参数设置
//        mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");
//        mTts.setParameter(SpeechConstant.SPEED, "50");//设置语速
//        mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量，范围 0~100
//        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
//        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
//        //开始合成
//        mTts.startSpeaking(text, null);
//    }

    //在获取的时间加任一时间
    public static String addDateMinut(String day, int x) {
        //返回的是字符串型的时间，输入的是String day, int x
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制
        //引号里面个格式也可以是 HH:mm:ss或者HH:mm等等，很随意的，不过在主函数调用时，要和输入的变量day格式一致
        Date date = null;
        try {
            date = format.parse(day);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (date == null)
            return "";
        System.out.println("front:" + format.format(date)); //显示输入的日期
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, x);// 24小时制
        date = cal.getTime();
        System.out.println("after:" + format.format(date));  //显示更新后的日期
        cal = null;
        return format.format(date);
    }

    //获取时间差
    public static long timeDValue(String time, String _time) {
        long returnMillis = 0;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        DateFormat df1 = new SimpleDateFormat("HH:mm:ss");
        try {
            Date d1 = df.parse(time);
            Date d2 = df.parse(_time);
            returnMillis = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
        } catch (Exception e) {
        }
//        return df1.format(returnMillis);
        return returnMillis;
    }

    //不能输入空格
    public InputFilter noKong(final int dends) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ") || source.toString().contentEquals("\n") || dend > dends) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        return filter;
    }

    //只能输入汉字、英文、数字
    public static InputFilter fileter() {
        InputFilter inputFilter = new InputFilter() {

            Pattern pattern = Pattern.compile("[^a-zA-Z0-9\\u4E00-\\u9FA5_]");

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher matcher = pattern.matcher(source);
                if (!matcher.find()) {
                    return null;
                } else {
                    ToastUtils.show("只能输入汉字,英文，数字");
                    return "";
                }
            }
        };
        return inputFilter;
    }

    //不能#&@%以及表情
    public static InputFilter inputFileter() {

        InputFilter inputFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "[&#@%]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (source.equals(" ") || source.toString().contentEquals("\n")) {
                    return "";
                } else if (matcher.find()) {
                    ToastUtils.show("不能输入&、#、@、%");
                    return "";
                } else {
                    return null;
                }
            }
        };
        return inputFilter;
    }

    /**
     * 给edittext设置过滤器 过滤emoji
     */
    public static InputFilter EmojiFilter() {
        InputFilter emojiFilter = new InputFilter() {
            Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher matcher = pattern.matcher(source);
                if (matcher.find()) {
                    ToastUtils.show("不能输入表情");
                    return "";
                }
                return null;
            }
        };
        return emojiFilter;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return Build.MODEL;
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }


    public static String listToString(List<Uri> list) {
        if (list == null) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        boolean first = true;

        //第一个前面不拼接","
        for (Uri string : list) {
            if (first) {
                first = false;
            } else {
                result.append(",");
            }
            result.append(string);
        }
        return result.toString();
    }

    //转换为年月的时间格式
    public static String getDate(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = new Date(time);
        return sf.format(d);
    }

    //转换为年月的时间格式
    public static String getDateDay(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("dd");
        Date d = new Date(time);
        return sf.format(d);
    }

    //转换为年月的时间格式
    public static String getDate11(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d = new Date(time);
        return sf.format(d);
    }

    //转换为时分的时间格式
    public static String getDateToString(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
        Date d = new Date(time);
        return sf.format(d);
    }

    //转换为年月日时分秒的时间格式
    public static String getDateToStringOne(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date(time);
        return sf.format(d);
    }

    //时分的时间格式转换为long
    public static long getLongTime(String str) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
        Date date = sf.parse(str);
        return date.getTime();
    }

    //时分的时间格式转换为long
    public static long getLongTime1(String str) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sf.parse(str);
        return date.getTime();
    }

    //时分的时间格式转换为long
    public static long getLongTime2(String str) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sf.parse(str);
        return date.getTime();
    }

    public static String listToStringBy(List<String> list){
        StringBuffer stringBuffer = new StringBuffer();
        for(int i=0;i<list.size();i++){
            stringBuffer.append(list.get(i)+" | ");
        }
        String dataUrl = stringBuffer.deleteCharAt(stringBuffer.length() - 2).toString();
        return dataUrl;
    }

    public static long getLong(String str) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
        Date date = sf.parse(str);
        return date.getTime();
    }

    public static long getLong1(String str) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sf.parse(str);
        return date.getTime();
    }

    public static BigDecimal halfUp(double value) {
        BigDecimal bg = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP);
        return bg;
    }

    public static String getPublicDateTimeAxis(Date date) {
        if (date == null) {
            return "";
        }
        Date current = new Date();
        int days = (int) ((new Date().getTime() - date.getTime()) / (1000 * 3600 * 24));
        if (days == 0) {
            long time = current.getTime() - date.getTime();
            long seconds = time / 1000;
            long minutes = seconds / 60;
            long hours = minutes / 60;
            if (minutes < 1) {
                return "刚刚";
            } else if (minutes >= 1 && minutes < 60) {
                return minutes + "分钟前";
            }
            return hours + "小时前";
        } else if (days == 1) {
            return "昨天";
        } else if (days <= 7) {
            return days + "天前 ";
        } else {
            return new SimpleDateFormat("yyyy年MM月dd日").format(date);
        }

    }

    public static final int SECONDS_IN_DAY = 60 * 60 * 24;
    public static final long MILLIS_IN_DAY = 1000L * SECONDS_IN_DAY;

    public static boolean isSameDayOfMillis(final long ms1, final long ms2) {
        final long interval = ms1 - ms2;
        return interval < MILLIS_IN_DAY
                && interval > -1L * MILLIS_IN_DAY
                && toDay(ms1) == toDay(ms2);
    }

    private static long toDay(long millis) {
        return (millis + TimeZone.getDefault().getOffset(millis)) / MILLIS_IN_DAY;
    }

//    public static String buildVideoMessage(Context context,String mUri) {
//        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
//        try {
//            mmr.setDataSource(mUri);
//            String sDuration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
//            Bitmap bitmap = mmr.getFrameAtTime(0, MediaMetadataRetriever.OPTION_NEXT_SYNC);
//            String imgPath = FileUtil.saveBitmap(context, bitmap);
//
//            return imgPath;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        } finally {
//            mmr.release();
//        }
//
//        return null;
//    }

    /**
     *
     * @param url 0是横图 1是竖图
     * @return true 是横图 false 是竖图
     */
    public static boolean getImageState(String url){
        String[] strs = url.split("_");
        if(url.contains("?")){//包含问号
            String[] ro =url.split("/");
            if(strs.length!=0&&ro.length!=0){
                if((strs[1].equals("0")&&ro[ro.length-1].equals("90"))||strs[1].equals("0")&&ro[ro.length-1].equals("270")){
                    return false;
                }else if((strs[1].equals("1")&&ro[ro.length-1].equals("90"))||strs[1].equals("1")&&ro[ro.length-1].equals("270")){
                    return true;
                }else if((strs[1].equals("0")&&ro[ro.length-1].equals("0"))||strs[1].equals("0")&&ro[ro.length-1].equals("180")||strs[1].equals("0")&&ro[ro.length-1].equals("360")){
                    return true;
                }else if((strs[1].equals("1")&&ro[ro.length-1].equals("0"))||strs[1].equals("1")&&ro[ro.length-1].equals("180")||strs[1].equals("1")&&ro[ro.length-1].equals("360")){
                    return false;
                }else{
                    return true;
                }
            }else{
                return true;
            }
        }else{
            if(strs.length != 0){
                if(strs[1].equals("0")){
                    return true;
                }else if(strs[1].equals("1")){
                    return false;
                }else{
                    return true;
                }
            }else{
                return true;
            }
        }
    }
}
